#include <stdio.h>
#include <stdlib.h>
#include "ia041.h"
int main(int argc, char * * argv)
{
  /* if argc is not 2, return EXIT_FAILURE */
  if (argc != 2)
    {
      printError(ARGC_ERROR);
      return EXIT_FAILURE;
    }
  /* open the input file whose name is given in argv[1] */
  FILE * fptr = fopen(argv[1], "r");
  
  /* if opening the file fails, return EXIT_FAILURE */
  if (fptr == NULL)
    {
      printError(FOPEN_ERROR);
      return EXIT_FAILURE;
    }
  
  /* count the number of integers in the file */
  int length = countInts(fptr);
  
  /* allocate memory to store the integers */
  int * array;
  array = malloc(sizeof(int) * length);
  /* if memory allocation fails, print error, close the file, and
     exit */
  if (array == NULL)
    {
      printError(MALLOC_ERROR);
      fclose (fptr);
      return EXIT_FAILURE;
    }
  /* read the integers from the file and stores them in the array */
  readInts(fptr, array, length);

  if (arePositive(array, length) == 1)
    { printf("All elements are positive.\n"); }
  else
    { printf("Not all elements are positive.\n"); }

  if (areIncreasing(array, length) == 1)
    { printf("Elements are increasing.\n"); }
  else
    { printf("Elements are not increasing.\n"); }

  if (areDistinct(array, length) == 1)
    { printf("Elements are distinct.\n"); }
  else
    { printf("Elements are not distinct.\n"); }

  /* release allocated memory */
  free (array);
  /* close the file */
  fclose (fptr);

  /* return EXIT_SUCCESS */
  return EXIT_SUCCESS;
}

void printError(int code)
{
  switch (code)
    {
    case ARGC_ERROR:
      printf("argc is not 2\n");
      break;
    case FOPEN_ERROR:
      printf("fopen fail\n");
      break;      
    case MALLOC_ERROR:
      printf("malloc fail\n");
      break;
    default:
      printf("unknown error code\n");
    }
}
